package com.localking.algorithm.leetcode.array.string

/**
 * Given two binary strings, return their sum (also a binary string).
 * The input string are both non-empty and contains only characters 1 or 0
 *
 * Example 1:
 * Input: a = "11", b = "1"
 * Output: "100"
 *
 * Example 2:
 * Input: a = "1010", b = "1011"
 * Output: "10101"
 *
 * @author jinbo
 */
object AddBinary {
  def main(args: Array[String]): Unit = {
    val a = "1010"
    val b = "1011"
    println(addBinary(a, b))
  }

  def addBinary(a: String, b: String): String = {
    if (a == "0") return b
    if (b == "0") return a
    var aStr = ""
    var bStr = ""
    val base = '0'.toInt
    val sizeA = a.length
    val sizeB = b.length
    var length = a.length
    if (sizeA > sizeB) {
      aStr = a
      bStr = "0" * (sizeA - sizeB) + b
    } else if (sizeA < sizeB) {
      length = b.length
      bStr = b
      aStr = "0" * (sizeB - sizeA) + a
    } else {
      aStr = a
      bStr = b
    }
    var resultArray: Array[Int] = Array.empty
    var carry = 0
    (length - 1 to 0 by -1).foreach(i => {
      val currentBitSum = aStr(i).toInt + bStr(i).toInt - base * 2 + carry
      carry = currentBitSum / 2
      resultArray +:= currentBitSum % 2
    })
    if (carry == 1) {
      resultArray +:= 1
    }
    resultArray.mkString
  }
}
